package com.ooo.ttt.opencvlib.camera;

import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class Cmare1Loader implements CameraLoader, Camera.PreviewCallback {
    private static final String TAG = "Cmare1Loader";
     private int mCameraID = Camera.CameraInfo.CAMERA_FACING_BACK;// BACK 是手机背面的摄像头  是 0
    //private int mCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;// FRONT 是手机屏幕这个方向的摄像头  是 1
    private int rotateDegree;
    private Camera mCamera;
    private byte[] cameraBuffer;
    private byte[] cameraBuffer_;
    private int mWidth = 800;
    private int mHeight = 400;
    private int mRotation;
    private Context context;
    private OnFrameDataListener mOnFrameListener;


    @Override
    public void initCamera(Context context) {
        this.context = context;
        try {
            // 获得camera对象
            mCamera = Camera.open(mCameraID);
            cameraBuffer = new byte[mWidth * mHeight * 3 / 2];
            cameraBuffer_ = new byte[mWidth * mHeight * 3 / 2];
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getCameraId() {
        return mCameraID;
    }

    @Override
    public void setSurface(SurfaceHolder holder) {

        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startPreview() {
        // 预览数据回调接口
        mCamera.setPreviewCallback(null);
        // 停止预览
        mCamera.stopPreview();


        rotateDegree = getCameraDegree();

        if (mCamera != null) {
            // 配置camera的属性
            Camera.Parameters parameters = mCamera.getParameters();
            // 设置预览数据格式为nv21
            parameters.setPreviewFormat(ImageFormat.NV21); // 属于yuv420
            // 这是摄像头宽、高
            setPreviewSize(parameters);


            mCamera.setDisplayOrientation(rotateDegree);

            mCamera.setParameters(parameters);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
        }
        // 数据缓存区
        mCamera.addCallbackBuffer(cameraBuffer);
        mCamera.setPreviewCallbackWithBuffer(this);
        mCamera.startPreview();
    }


    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

        int imageWidth = camera.getParameters().getPreviewSize().width;
        int imageHeight = camera.getParameters().getPreviewSize().height;
        if (mOnFrameListener != null) {
            mOnFrameListener.onPreviewFrame(data, imageWidth, imageHeight, rotateDegree);
        }
        camera.addCallbackBuffer(cameraBuffer);
    }

    @Override
    public void switchCamera() {
        if (mCameraID == Camera.CameraInfo.CAMERA_FACING_BACK) {
            mCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
        } else {
            mCameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
        }

        startPreview();
    }


    @Override
    public void setOnFrameDataListener(OnFrameDataListener listener) {
        mOnFrameListener = listener;
    }

    @Override
    public void stopCamera() {
        if (mCamera != null) {
            // 预览数据回调接口
            mCamera.setPreviewCallback(null);
            // 停止预览
            mCamera.stopPreview();
            // 释放摄像头
            mCamera.release();
            mCamera = null;
        }
    }


    private int getCameraDegree() {
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        Camera.getCameraInfo(mCameraID, cameraInfo);
        mRotation = ((Activity) context).getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (mRotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90: // 横屏 左边是头部(home键在右边)
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;

                break;
            case Surface.ROTATION_270:// 横屏 头部在右边
                degrees = 270;

                break;
        }
        int result;
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (cameraInfo.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else { // back-facing
            result = (cameraInfo.orientation - degrees + 360) % 360;
        }
        // 设置角度, 参考源码注释
        mCamera.setDisplayOrientation(result);
        return result;
    }

    private void setPreviewSize(Camera.Parameters parameters) {
        // 获取摄像头支持的宽、高
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        Camera.Size size = supportedPreviewSizes.get(0);
//        Log.d(TAG, "Camera支持: " + size.width + "x" + size.height);
        // 选择一个与设置的差距最小的支持分辨率
        int m = Math.abs(size.width * size.height - mWidth * mHeight);
        supportedPreviewSizes.remove(0);
        Iterator<Camera.Size> iterator = supportedPreviewSizes.iterator();
        // 遍历
        while (iterator.hasNext()) {
            Camera.Size next = iterator.next();
//            Log.d(TAG, "支持 " + next.width + "x" + next.height);
            int n = Math.abs(next.height * next.width - mWidth * mHeight);
            if (n < m) {
                m = n;
                size = next;
            }
        }
        mWidth = size.width;
        mHeight = size.height;
        parameters.setPreviewSize(mWidth, mHeight);
//        Log.d(TAG, "预览分辨率 width:" + mWidth + " height:" + mHeight);
    }
}
